package hcs.model;

import hcs.HouseController;
import hcs.interfaces.ClockObserver;
import hcs.interfaces.StateObservable;

import java.util.Observable;
import stubs.IPhysicalEnvironment;
import stubs.PhysicalFactory;

/**
 * A proxy class registered on {@link Clock}, which polls
 * {@link IPhysicalEnvironment} on every {@link Clock#tic}
 */
public class Environment extends StateObservable implements ClockObserver {
	private IPhysicalEnvironment physicalEnvironment;
	private double temperature;
	private boolean isRaining;
	private long seconds;
	
	/**
	 * Creates a new environement.
	 * @param env {@link IPhysicalEnvironment}
	 * @param hC the {@link HouseController} object
	 */
	public Environment() {
		this.physicalEnvironment = PhysicalFactory.getPhysicalEnvironment();
		Clock.getInstance().addObserver(this);
		temperature = physicalEnvironment.getTemperature();
		isRaining = physicalEnvironment.isRainingSwitchClosed();
		seconds = 0;
	}
	
	/**
	 * @return the outside temperature
	 */
	public double getTemperature() {
		return temperature;
	}
	
	/**
	 * 
	 * @return true if it's raining
	 */
	public boolean isRaining() {
		return isRaining;
	}
	
	/**
	 * 
	 * @return the number of secods elapsed since system start
	 */
	public long getSecondsSinceStart() {
		return seconds;
	}
	
	/**
	 * Force polling
	 * @param o not used
	 * @param arg not used
	 */
	public void update(Observable o, Object arg) {
		double t = this.physicalEnvironment.getTemperature();
		boolean isR = this.physicalEnvironment.isRainingSwitchClosed();
		if(this.isRaining != isR || this.temperature != t) { 
			this.setChanged();
			this.isRaining = isR;
			this.temperature = t;
		}
		seconds = this.physicalEnvironment.getSecondsSinceStart();
		this.notifyObservers();
	}
}
